package com.atguigu.sync;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 张晓
 * @create 2020-12-25 14:23
 */
public class TestReentrantLock {

    private static ReentrantLock lock = new ReentrantLock();

    private static int taskNum = 100;//任务数量

    private static int poolSize = 10;//线程池数量

    private static CountDownLatch latch = new CountDownLatch(taskNum);

    private static int count;//计数器

    private static AtomicInteger atomicInteger = new AtomicInteger(1);


    //计数器递增
    public static void increment() {
        count++;
        System.out.println("当前线程名字：" + Thread.currentThread().getName() + " 当前count: " + count);
    }

    public static void main(String[] args) throws Exception {
        //测试可重入锁
        //testReentrantLock();
        //测试AtomicInteger
        testAtomicInteger();
    }


    public static void testReentrantLock() throws InterruptedException {

        System.out.println("=======================开始执行时间："+System.currentTimeMillis()+"========================");
        ExecutorService pool = Executors.newFixedThreadPool(poolSize);
        for (int i = 0; i < taskNum; i++) {
            pool.execute(new Runnable() {
                public void run() {
                    try {
                        lock.lock();
                        increment();
                        latch.countDown();
                    } finally {
                        lock.unlock();
                    }
                }
            });
        }
        latch.await();
        System.out.println("=======================结束执行时间："+System.currentTimeMillis()+"========================");
        pool.shutdown();
    }


    public static void testAtomicInteger() throws InterruptedException {

        System.out.println("=======================开始执行时间："+System.currentTimeMillis()+"========================");
        ExecutorService pool = Executors.newFixedThreadPool(poolSize);
        for (int i = 0; i < taskNum; i++) {
            pool.execute(new Runnable() {
                public void run() {
                    //int increment = atomicInteger.getAndIncrement();
                    int increment = atomicInteger.getAndAdd(1);
                    System.out.println(increment);
                    latch.countDown();
                }
            });
        }
        latch.await();
        System.out.println("=======================结束执行时间："+System.currentTimeMillis()+"========================");
        pool.shutdown();
    }



}
